package stiletto.user.dao.impl;

import org.springframework.dao.DataRetrievalFailureException;
import org.springframework.stereotype.Repository;
import stiletto.user.dao.UserDao;
import stiletto.user.domain.User;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.PersistenceContextType;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: 82022170
 * Date: 13. 10. 28
 * Time: 오후 3:55
 * To change this template use File | Settings | File Templates.
 */
// todo: NamedQuery 어노테이션이 왜 안 먹는지 원인 파악
@Repository
public class UserDaoJpaImpl implements UserDao {
  @PersistenceContext(type = PersistenceContextType.TRANSACTION)
  private EntityManager em;

  public EntityManager getEntityManager() {
    return em;
  }

  public void setEntityManager(EntityManager newEntityManager) {
    em = newEntityManager;
  }

  /**
   * @param user
   */
  @Override
  public void insert(User user) {
    em.persist(user);
  }

  /**
   * @param user
   */
  @Override
  public void update(User user) {
    em.merge(user);
  }

  /**
   * @param user DB에서 삭제(delete)할 사용자
   */
  @Override
  public void delete(User user) {
    em.remove(em.contains(user) ? user : em.merge(user));
  }

  /**
   *
   * @param email
   * @return
   * @throws DataRetrievalFailureException
   */
  @Override
  public User findOneUser(String email) throws DataRetrievalFailureException {
    User found = em.find(User.class, email);

    if (null == found) throw new DataRetrievalFailureException("email = " + email);

    return found;
  }

  /**
   *
   * @param screenName
   * @return
   * @throws DataRetrievalFailureException
   */
  @Override
  public List<User> findUsersByScreenName(String screenName) {
    // todo - Paging 구현
    List<User> found = em.createQuery("select u from User u where u.screenName like '" + screenName + "%'", User.class).getResultList();

    if (null == found || 0 == found.size()) throw new DataRetrievalFailureException("screenName = " + screenName);

    return found;
  }

  /**
   *
   * @return
   * @throws DataRetrievalFailureException
   */
  @Override
  public List<User> findAllUsers() throws DataRetrievalFailureException {
    // todo - Paging 구현
    List<User> found = em.createQuery("select u from User u", User.class).getResultList();

    if (null == found || 0 == found.size()) throw new DataRetrievalFailureException("NO USER AT ALL!");

    return found;
  }
}
